package com.cntv.viewmodeldemo.savestate;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.SavedStateHandle;
import androidx.lifecycle.ViewModel;

import com.cntv.viewmodeldemo.R;

/**
 * Created By Mahongyin
 * Date    2020/9/17 15:53
 * 数据又深了一层  交给了 VM的SavedStateHandle去保存。这样activity在被意外杀死 可保障数据恢复
 * */
public class MySavaStateViewModel extends ViewModel {
    SavedStateHandle handle;
    public String key="save_key";
    public MySavaStateViewModel(SavedStateHandle stateHandle) {
        handle=stateHandle;
        if (!handle.contains(key)){//如果不包含就是没保存过 判断应该是初始状态 那么给他一个初始值
            handle.set(key,0);//SavedStateHandle(Map<String, Object> initialState)
        }
    }

    public MutableLiveData<Integer> getNum() {

        return handle.getLiveData(key);//将数据来源替换成 VM的SavedStateHandle保存的

    }

    public void add(int n) {
//        number.setValue(number.getValue()+n);
        //将数据来源替换给 VM的SavedStateHandle
        handle.set(key,(int)handle.get(key)+n);
    }
}
